"""Functions for building and using various ui elements"""

from pyre.core import types

def popup_selector(term, items, title):
    """
    popup_selector(Terminal, list, str): object
    Creates an alphabetic selector and returns the selected object, or None if
    the selection was invalid.
    """

    term.save_buffer()

    items = list(items)
    rows = [title]
    rows += ['{}) {}'.format(chr(n), i) for n, i in enumerate(items, ord('a'))]
    max_len = max(len(row) for row in rows)

    for y, row in enumerate(rows):
        for x in range(max_len):
            if x < len(row):
                term.buffer_char((x, y), types.ColoredChar(row[x]))
            else:
                term.buffer_char((x, y), types.ColoredChar(' '))
    term.refresh_screen()

    try:
        key = term.get_key()
        return items[ord(key) - ord('a')]
    except IndexError:
        return None
    finally:
        term.recall_buffer()
        term.refresh_screen()


def popup_text(term, text):
    """
    popup_text(Terminal, str): None
    Displays the text centered on the Terminal screen until a key is pressed
    """

    term.save_buffer()

    text = text.split('\n')
    for y, row in enumerate(text, (term.rows - len(text)) // 2):
        for x, ch in enumerate(row, (term.cols - len(row)) // 2):
            term.buffer_char((x, y), types.ColoredChar(ch))
    term.refresh_screen()
    term.get_key()

    term.recall_buffer()
    term.refresh_screen()
